package com.uairobot.bill.yz.office.agent.service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Date;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.uairobot.bill.yz.office.agent.entity.UploadFile;
import com.uairobot.bill.yz.office.agent.repository.UploadFileRepository;
import com.uairobot.bill.yz.office.agent.utils.FileTypeUtil;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class BillUploadService {
  @Autowired
  private FileSaveSerivce fileSaveSerivce;
  @Autowired
  private UploadFileRepository uploadFileRepository;

  /**
   * 1.获取文件md5,查询数据库 2.数据库中不存在,上传文件,保存到数据,返回
   * 
   */
  public UploadFile upload(MultipartFile file) {
    byte[] bytes = null;
    try {
      bytes = file.getBytes();
    } catch (IOException e) {
      e.printStackTrace();
    }
    // 文件名
    String originalFileName = file.getOriginalFilename();
    // 拓展名
    String extension = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);
    UploadFile upload = upload(originalFileName, bytes, extension, null);
    return upload;

  }

  /**
   * @param extension
   * @param folder
   *          如果没有,设置为null
   * @return
   */
  public UploadFile upload(String filename, byte[] bytes, String extension, String folder) {
    String md5Hex = DigestUtils.md5Hex(bytes);
    log.info("文件总大小:{}B", bytes.length);
    UploadFile uploadFile = uploadFileRepository.findByMd5(md5Hex);
    if (uploadFile != null) {
      log.info("从数据库中查找到:{},md5:{}",uploadFile.getUri(),md5Hex);
      return uploadFile;
    }

    // 文件输入流
    ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
    String uri = fileSaveSerivce.saveInputStream(inputStream, md5Hex,bytes.length, extension, folder,filename);

    log.info("接收上传文件成功,保存位置,{},文件md5:{}", fileSaveSerivce.getLocalFilePath(uri),md5Hex);
    UploadFile retval = new UploadFile();
    retval.setMd5(md5Hex);
    retval.setUri(uri);
    retval.setFilename(filename);
    retval.setSize(bytes.length);
    retval.setUploadTime(new Date());
    retval.setType(FileTypeUtil.getType(extension));
    
    
    //retval.setLocalFilePath(fileSaveSerivce.getLocalFilePath(retval.getUri()));
    uploadFileRepository.save(retval);
    return retval;
  }

  public String getFullUriById(String md5Hex) {
    UploadFile uploadFile = uploadFileRepository.findByMd5(md5Hex);
    String uri = null;
    if (uploadFile != null) {
      uri = uploadFile.getUri();
      // log.info("从数据中查询到到图片:" + md5Hex+","+uri);
    }
    uri = fileSaveSerivce.getFullUri(uri);
    return uri;
  }
}